package com.jsmy.softapp.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.ButtonBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.jsmy.softapp.MyApp;
import com.jsmy.softapp.R;
import com.jsmy.softapp.aroute.AR;
import com.jsmy.softapp.net.API;
import com.jsmy.softapp.net.NetWork;
import com.jsmy.softapp.presenter.MinePresenter;
import com.jsmy.softapp.util.MyLog;
import com.jsmy.softapp.util.SPF;
import com.jsmy.softapp.util.ShareUtil;
import com.jsmy.softapp.util.ToastUtil;
import com.jsmy.softapp.view.MineView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.functions.Consumer;

@Route(path = AR.A_MINE)
public class MineActivity extends BaseActivity<MineView, MinePresenter> implements MineView, UMShareListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.buttonBarLayout)
    ButtonBarLayout buttonBarLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.img_bg)
    ImageView imgBg;
    @BindView(R.id.img_avatar)
    CircleImageView imgAvatar;

    boolean isAvatar;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.toolbar_avatar)
    CircleImageView toolbarAvatar;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.m_webview)
    WebView mWebview;

    String sharePt = "";
    String shareId = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mine;
    }

    @Override
    protected MinePresenter createPresenter() {
        return new MinePresenter();
    }

    @Override
    protected void initView() {
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MineActivity.this.finish();
            }
        });
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        }
        appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                if (i == 0) {
                    buttonBarLayout.setVisibility(View.GONE);
                } else if (Math.abs(i) >= appBarLayout.getTotalScrollRange()) {
                    buttonBarLayout.setVisibility(View.VISIBLE);
                } else {
                    buttonBarLayout.setVisibility(View.GONE);
                }
            }
        });
        NetWork.setImageGlide(this, MyApp.getMyApp().bean.getIco(), imgAvatar);
        NetWork.setImageGlide(this, MyApp.getMyApp().bean.getIco(), toolbarAvatar);
        tvName.setText(MyApp.getMyApp().bean.getUsername());
        title.setText(MyApp.getMyApp().bean.getUsername());
        tvContent.setText(MyApp.getMyApp().bean.getTitle());

        mWebview.setVerticalScrollbarOverlay(true); //指定的垂直滚动条有叠加样式
        WebSettings settings = mWebview.getSettings();
        settings.setUseWideViewPort(true);//设定支持viewport
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setBuiltInZoomControls(true);
        settings.setSupportZoom(true);//设定支持缩放
        settings.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebview.clearHistory();
        mWebview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

                return super.shouldOverrideUrlLoading(view, request);
            }
        });

        mWebview.loadUrl(API.APP_SHARE + SPF.getString(MyApp.getMyApp(), SPF.SP_ZH, MyApp.getMyApp().bean.getUsername()));

    }

    @Override
    protected void initData() {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showLoadingData(String type, Object object) {

    }

    private void showPhotoDialog(final boolean isAvatar) {
        this.isAvatar = isAvatar;
        final BottomSheetDialog dialog = new BottomSheetDialog(this);
        dialog.setContentView(R.layout.bottom_sheet_photo);
        dialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(android.R.color.transparent);
        TextView tvTakePhoto = (TextView) dialog.findViewById(R.id.tv_take_photo);
        tvTakePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    if (isAvatar) {
                                        getAvatarFroCamera();
                                    } else {
                                        getPitureForCamera();
                                    }
                                } else {
                                    ToastUtil.showLong(MineActivity.this, "缺少权限，请授予相机和SD卡的使用权限！");
                                }
                            }
                        });
                dialog.dismiss();
            }
        });
        TextView tvPhotoAlbum = (TextView) dialog.findViewById(R.id.tv_photo_album);
        tvPhotoAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    if (isAvatar) {
                                        getAvatarForGallery();
                                    } else {
                                        getPitureForGallery();
                                    }
                                } else {
                                    ToastUtil.showLong(MineActivity.this, "缺少权限，请授予相机和SD卡的使用权限！");
                                }
                            }
                        });
                dialog.dismiss();
            }
        });
        TextView tvCancel = (TextView) dialog.findViewById(R.id.tv_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        presenter.model.disposable.clear();
        super.onDestroy();
    }

    @OnClick({R.id.img_bg, R.id.img_avatar, R.id.btn_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_bg:
//                showPhotoDialog(false);
                break;
            case R.id.img_avatar:
//                showPhotoDialog(true);
                break;
            case R.id.btn_share:
                ShareUtil.shareWeb(this, API.APP_SHARE, "金牌销售", "金牌销售", this);
                break;
        }
    }

    private void getPitureForGallery() {
        PictureSelector.create(MineActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .isCamera(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void getPitureForCamera() {
        PictureSelector.create(MineActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void getAvatarForGallery() {
        PictureSelector.create(MineActivity.this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .isCamera(false)
                .enableCrop(true)
                .withAspectRatio(1, 1)
                .circleDimmedLayer(true)
                .showCropFrame(false)
                .showCropGrid(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void getAvatarFroCamera() {
        PictureSelector.create(MineActivity.this)
                .openCamera(PictureMimeType.ofImage())
                .enableCrop(true)
                .withAspectRatio(1, 1)
                .circleDimmedLayer(true)
                .showCropFrame(false)
                .showCropGrid(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    for (LocalMedia media : selectList) {
                        if (isAvatar) {
                            if (media.isCut()) {
                                MyLog.showLog(TAG, media.getCutPath());
                            } else {
                                MyLog.showLog(TAG, media.getPath());
                            }
                        } else {
                            MyLog.showLog(TAG, media.getPath());
                        }
                    }
                    //包括裁剪和压缩后的缓存，要在上传成功后调用，注意：需要系统sd卡权限
                    PictureFileUtils.deleteCacheDirFile(MineActivity.this);
                    break;
            }
        }
    }

    @Override
    public void onStart(SHARE_MEDIA share_media) {

    }

    @Override
    public void onResult(SHARE_MEDIA platform) {
        switch (platform) {
            case QQ:
                sharePt = "QQ";
                break;
            case QZONE:
                sharePt = "QZONE";
                break;
            case SINA:
                sharePt = "SINA";
                break;
            case WEIXIN:
                sharePt = "WEIXIN";
                break;
            case WEIXIN_CIRCLE:
                sharePt = "WEIXIN_CIRCLE";
                break;
            case SMS:
                sharePt = "SMS";
                break;
            case EMAIL:
                sharePt = "EMAIL";
                break;
        }
        presenter.savefxinfo(shareId, "", sharePt, "");
    }

    @Override
    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
        ToastUtil.showShort(this, "分享失败，" + throwable.getMessage());
    }

    @Override
    public void onCancel(SHARE_MEDIA share_media) {
        ToastUtil.showShort(this, "分享取消");
    }
}
